<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>新增学生信息</title>
    <link rel="stylesheet" href="js/layui/css/layui.css" media="all">
    <style type="text/css">
        .newTraining_sample .layui-form-label {
            width: 115px;
        }

        .layui-form-item .layui-input-inline {
            width: 360px;
        }
    </style>
</head>

<body>
<div style="padding: 40px; background-color: #F2F2F2;">
    <div class="layui-card">
        <form class="layui-form" method="post">
            <div class="layui-card-header" style="font-weight:bold;font-size: 18px;padding: 0px 100px">新增学生信息</div>
            <div class="layui-card-body newStudent">
                <div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">学号</label>
                        <div class="layui-input-inline">
                            <input type="number" id="stu_id" name="stu_id" required lay-verify="required|id" placeholder="请填写学号" autocomplete="on" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">姓名</label>
                        <div class="layui-input-inline">
                            <input type="text" id="name" name="name" required lay-verify="required|name"
                                   placeholder="请填写姓名" autocomplete="on" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">邮箱</label>
                        <div class="layui-input-inline">
                            <input type="text" id="email" name="email" required lay-verify="required|email" placeholder="请填写邮箱" autocomplete="on" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">出生日期</label>
                        <div class="layui-input-inline">
                            <input type="date" id="birthdate" onblur="calculateAge()" name="birthdate" required lay-verify="required" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">年龄</label>
                        <div class="layui-input-inline">
                            <input type="number" id="age" name="age" class="layui-input" readonly>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">性别</label>
                        <div class="layui-input-inline">
                            <select name="sex" lay-verify="required" lay-search="" lay-filter="sex">
                                <option value="">请选择性别</option>
                                <option value="0">男</option>
                                <option value="1">女</option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">手机号码</label>
                        <div class="layui-input-inline">
                            <input type="number" id="phone" name="phone" required lay-verify="required|phone" placeholder="请输入手机号码" autocomplete="on" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">上传近期免冠照片</label>
                        <div class="layui-upload">
                            <button type="button" class="layui-btn" id="choosePhoto" style="vertical-align: top">选择</button>
                            <div style="display: inline-block; margin-top: -10px; text-align: center">
                                <div class="layui-upload-list">
                                    <img class="layui-upload-img" width="160" height="160" id="upload_photo">
                                    <p id="upload_result"></p>
                                </div>
                                <div>
                                    <div class="layui-progress layui-progress-big" lay-showpercent="yes" lay-filter="upload_progress">
                                        <div class="layui-progress-bar" lay-percent=""></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-input-block">
                            <input type="button" class="layui-btn" lay-submit lay-filter="submit_servlet" value="提交到servlet" />
                            <input type="button" class="layui-btn" lay-submit lay-filter="submit_struts2" value="提交到struts2" />
                            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>
<script src="js/layui/layui.js" charset="utf-8"></script>
<script>
    var $;
    layui.use(['form', 'upload', 'element', 'layer'], function () {
        const form = layui.form;
        const upload = layui.upload;
        const element = layui.element;
        const layer = layui.layer;
        $ = layui.jquery;

        // 渲染表单元素
        form.render();
        // 点击按钮提交到servlet
        const index = parent.layer.getFrameIndex(window.name);//获取窗口索引

        // 渲染文件上传
        //常规使用 - 普通图片上传
        var photo_base64;
        const uploadInst = upload.render({
            elem: '#choosePhoto'
            // , url: 'addStudent' //改成您自己的上传接口
            , field: 'photo'
            , auto: false   // 不手动进行提交
            // , bindAction: '#btn_servlet' // 绑定按钮触发上传
            , size: 1024 * 2 // 限制图片不超过2M大小
            , before: function (obj) {
                layer.load('上传中', {icon: 16, time: 0});
            }
            , accept: "images" // 指定允许上传时校验的文件类型，可选值有：images（图片）、file（所有文件）、video（视频）、audio（音频）
            , acceptMime: "image/*" // acceptMime: 'image/jpg, image/png'，只显示 jpg和png文件；acceptMime: 'image/*'（只显示图片文件）
            , done: function (res) {
                //如果上传失败
                if (res.code > 0) {
                    return layer.msg('上传失败');
                }
                //上传成功的一些操作
                $('#upload_result').html(''); //置空上传失败的状态

                layer.closeAll('loading'); //关闭loading
                parent.layer.close(index);
                parent.layui.table.reload("table_student");
            }
            , error: function () {
                //演示失败状态，并实现重传
                var upload_result_text = $('#upload_result');
                upload_result_text.html('<span style="color: #FF5722;">上传失败，请重试！</span>');
                // upload_result_text.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                // upload_result_text.find('.demo-reload').on('click', function () {
                //     uploadInst1.upload();
                // });
                layer.closeAll('loading'); //关闭loading
            }
            //进度条
            // , progress: function (n, elem, e) {
            //     element.progress('demo', n + '%'); //可配合 layui 进度条元素使用
            //     if (n == 100) {
            //         layer.msg('上传完毕', {icon: 1});
            //     }
            // }
            // 选择完图片之后先显示出来
            , choose: function(obj) {
                //预读本地文件示例，不支持ie8
                obj.preview(function (index, file, result) {
                    $('#upload_photo').attr('src', result); //图片链接（base64）
                    photo_base64 = result;
                });

                element.progress('upload_progress', '0%'); //进度条复位
                // layer.msg('上传中', {icon: 16, time: 0});
            }
        });

        // 监听提交
        // 提交到servlet
        // 点击按钮提交到servlet
        form.on('submit(submit_servlet)', function (data) {
            submitFormAndUploadPhoto('addStudent', data);

            return false;
        });
        // 点击按钮提交到struts2
        form.on('submit(submit_struts2)', function (data) {
            submitFormAndUploadPhoto('addStudent.action', data);

            return false;
        });

        function submitFormAndUploadPhoto(url, data) {
            data.field.photo_base64 = photo_base64;
            // console.log(data.field);
            uploadInst.reload({
                url: url,
                data: data.field
            });
            uploadInst.upload();
        }

        form.verify({
            id: function(value, item){ //value：表单的值、item：表单的DOM对象
                if (value.length != 10) {
                    return '装备编号长度必须为10个字符！';
                }
                //自定义ajax校验规则
                var result = '';
                $.ajax({
                    type: "POST",
                    url: "checkStuIdIfExist",
                    data:{"stu_id": value},
                    /*contentType:"application/json;charset=UTF-8",*/
                    async: false,
                    dataType: "json",
                    success: function (flag) {
                        if (flag.ifExist) {
                            result = '该学号已存在！';
                            console.log(result);
                        }
                    },
                    error: function () {

                    }
                });
                if (result != '') {
                    return result;
                }
            }
            ,name: function (value, item) {
                if (!/^[a-zA-Z0-9\u4e00-\u9fa5]+$/.test(value)) {
                    return '姓名中不能有特殊字符！';
                }
            }
            , email: function (value, item) {
                if (!/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(value)) {
                    return "邮箱格式不正确！";
                }
            }
            , phone: function (value, item) {
                if (!/^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/.test(value)) {
                    return "手机号码格式不正确！";
                }
            }

        });

    });

    // 计算年龄
    function calculateAge() {
        // 获取日期
        // console.log($("#birthdate").val());
        var strs = $("#birthdate").val().split("-");
        var year = parseInt(strs[0]);
        var month = parseInt(strs[1]);
        var day = parseInt(strs[2]);
        var date = new Date();
        var age = date.getFullYear() - year;
        if (date.getMonth() < month || date.getDate() < day) {
            age--;
            age = age < 0 ? 0 : age;
        }
        $("#age").val(age)
    }
</script>
</body>

</html>